<script setup>
import { ref } from "vue";
import { getFarmerApplyList } from "@/api/farmerApplication";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";

const userStore = useUserStore();

const applicationDetail = ref(null);

const List = ref([]);
const params = ref({ current: 1, size: 10, keyword: "" });
const total = ref(0);
const loading = ref(false);
const processedList = ref([]);

// 获取状态标签
const getStatusTag = (status) => {
  switch (status) {
    case 0:
      return { text: "待审核", type: "warning" };
    case 1:
      return { text: "已通过", type: "success" };
    case 2:
      return { text: "驳回", type: "danger" };
    default:
      return { text: "未知状态", type: "info" };
  }
};

// 进度图标
const getProgressIcon = (status) => {
  switch (status) {
    case "completed":
      return "el-icon-check";
    case "processing":
      return "el-icon-loading";
    case "success":
      return "el-icon-circle-check";
    case "failed":
      return "el-icon-circle-close";
    default:
      return "el-icon-info";
  }
};

// 进度颜色
const getProgressColor = (status) => {
  switch (status) {
    case "completed":
      return "#909399";
    case "processing":
      return "#409EFF";
    case "success":
      return "#67C23A";
    case "failed":
      return "#F56C6C";
    default:
      return "#909399";
  }
};

// 获取申请列表
const getList = async () => {
  loading.value = true;
  const res = await getFarmerApplyList(params.value);
  List.value = res.data.data.data || [];
  total.value = res.data.data.total || 0;
  // 处理进度数据
  processedList.value = List.value.map((item) => {
    const progress = [
      { title: "提交申请", time: item.applicationTime, status: "completed" },
    ];
    !item.auditTime
      ? progress.push({ title: "审核中", time: null, status: "processing" })
      : progress.push(
          { title: "审核完成", time: item.auditTime, status: "completed" },
          {
            title: item.status === 1 ? "申请通过" : "申请驳回",
            time: item.auditTime,
            status: item.status === 1 ? "success" : "failed",
            remark: item.auditRemark || "",
          }
        );
    return { ...item, progress };
  });
  loading.value = false;
};

getList();

// 分页/页大小变化
const handlePageChange = (page) => {
  params.value.current = page;
  getList();
};
const handleSizeChange = (size) => {
  params.value.size = size;
  params.value.current = 1;
  getList();
};

// 查看详情
const handleViewDetail = (row) => {
  console.log("查看详情:", row);
  applicationDetail.value.handleOpen(row, "detail");
};
// 农户申请
const addFarmerApply = () => {
  applicationDetail.value.handleOpen({}, "add");
};

// 回调
const success = () => {
  getList();
};
</script>

<template>
  <div class="farmerApply">
    <el-row :gutter="10">
      <!-- 申请记录表格 -->
      <el-col :span="14">
        <el-card shadow="never">
          <div slot="header" class="card-header">
            <span>申请记录</span>
            <el-button
              v-if="userStore.userInfo.roleType != 2"
              type="primary"
              :icon="Plus"
              @click="addFarmerApply"
              plain
              size="small"
              >申请</el-button
            >
          </div>
          <el-table
            :data="List"
            stripe
            :loading="loading"
            style="width: 100%"
            :default-sort="{ prop: 'applicationTime', order: 'descending' }"
            highlight-current-row
            @row-click="handleViewDetail"
          >
            <el-table-column
              type="index"
              label="序列"
              width="80"
              align="center"
            />
            <el-table-column
              prop="realName"
              label="申请人"
              width="80"
              align="center"
            />
            <el-table-column
              prop="idCard"
              label="身份证号"
              width="180"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.idCard.replace(
                    /(\d{6})(\d{8})(\d{4})/,
                    "$1********$3"
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="100"
              align="center"
            >
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status).type">
                  {{ getStatusTag(scope.row.status).text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="applicationTime"
              label="申请时间"
              width="160"
              align="center"
              sortable
            />

            <template #empty>
              <el-empty description="没有数据" />
            </template>
          </el-table>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              :current-page="params.current"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="params.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="Number(total)"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 最新进度跟踪（修复ElTimelineItem的size属性问题） -->
      <el-col :span="10">
        <el-card shadow="never">
          <div slot="header">最新进度跟踪</div>
          <div
            class="progress-tracking"
            style="max-height: 600px; overflow-y: auto; padding-right: 8px"
          >
            <div
              v-for="(apply, idx) in processedList.slice(0, 5)"
              :key="apply.applicationId"
              class="apply-item"
            >
              <div class="apply-title">
                <h4>{{ idx + 1 }}. {{ apply.realName }} 的申请</h4>
                <el-tag :type="getStatusTag(apply.status).type" size="small">
                  {{ getStatusTag(apply.status).text }}
                </el-tag>
              </div>
              <!-- 关键修复：删除 ElTimelineItem 上的 size="small" 属性 -->
              <el-timeline :reverse="true" class="mt-2">
                <el-timeline-item
                  v-for="(step, sIdx) in apply.progress"
                  :key="sIdx"
                  :timestamp="step.time || '——'"
                  :icon="getProgressIcon(step.status)"
                  :color="getProgressColor(step.status)"
                >
                  <div class="step-content">
                    <p class="step-title">{{ step.title }}</p>
                    <p v-if="step.remark" class="step-remark">
                      意见：{{ step.remark }}
                    </p>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>

            <div v-if="processedList.length === 0" class="empty-state">
              暂无申请进度记录
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <FarmerApplyDetail ref="applicationDetail" @success="success" />
</template>

<style scoped lang="scss">
.farmerApply {
  padding: 20px 50px;
  width: auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 5px;
}
.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 进度跟踪样式 */
.progress-tracking {
  padding: 10px 0;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background: #ccc;
  }
}
.apply-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }
}
.apply-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}
.step-content {
  .step-title {
    font-size: 14px;
    margin-bottom: 2px;
  }
  .step-remark {
    font-size: 12px;
    color: #666;
    margin: 0;
  }
}
.el-timeline {
  margin-left: 5px;
}
.el-timeline-item__timestamp {
  font-size: 12px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #999;
  background-color: #fafafa;
  border-radius: 4px;
}
</style>
